<template>
    <a-modal :title="title" :width="1200" :destroyOnClose="true" :maskClosable="false"
             :visible="visible" @cancel="handleCancel"
             :bodyStyle="{backgroundColor:'#F8F8F8' ,padding:'8px 16px'}">
        <a-row :gutter="[16,16]" type="flex" style="min-height: 500px">
            <a-col :span="8" flex="auto">
                <ItemList class="flexCol padded10"
                          :dataIndex="dataIndex"
                          :isUpdate="isUpdate"
                          :dataList="newsList"
                          @indexUp="indexUp"
                          @indexDown="indexDown"
                          @onAddItem="onAddItem"
                          @onRemove="onRemove"
                          @onChange="(key)=>{ this.dataIndex=key;}"
                />
            </a-col>
            <a-col :span="16" flex="auto">
                <div class="flexCol padded10">
                    <ItemEditor v-if="dataIndex>=0" :dataIndex="dataIndex" :dataList="newsList"/>
                </div>
            </a-col>
        </a-row>
        <!-- Modal 页脚 -->
        <template slot="footer">
            <a-row :gutter="16">
                <a-col :span="20" class=" text-right text-aux ">修改图文素材时 保存功能只对当前修改的图文有效</a-col>
                <a-col :span="4" class="text-center">
                    <a-button @click="handleCancel">关闭</a-button>
                    <a-button type="danger" :loading="loading" @click="updateArticle" v-if="isUpdate">保存修改</a-button>
                    <a-button type="primary" :loading="loading" @click="saveNewsMaterial" v-else>发布素材</a-button>
                </a-col>
            </a-row>
        </template>
    </a-modal>
</template>
<script>
    import Schema from 'async-validator';
    import {formRule} from './validator'
    import {addNewsMaterial, updateMaterialArticle} from '../../../public/http'
    import {getMaterialNews} from '../../../../../../util/internal.api'
    export default {
        props: ['mediaId'],
        components: {
            ItemList: () => import('./ItemList'),
            ItemEditor: () => import('./ItemEditor')
        },
        data() {
            return {
                visible: true, //modal 显示状态
                loading: false, //按钮Loading
                isUpdate: false,
                title: "新增图文素材",
                newsList: [],
                dataIndex: -1,
                errmsg: "",
                rules:formRule(), //表单验证规则
            };
        },
        methods: {
            //关闭弹窗
            handleCancel() {
                this.visible = false;
                this.$emit('closeModal', {
                    render: false
                });
            },
            //保存修改的图文
            updateArticle() {
                this.errmsg = "";
                let data=this.newsList[this.dataIndex];
                this.validator(this.dataIndex, data);
                if (this.errmsg.length > 0) {
                    this.$notification.error({message: '图文表单验证失败', description:this.errmsg })
                    return false;
                }
                let wxMpMaterialArticleUpdate = {
                    mediaId: this.mediaId,
                    index: this.dataIndex,
                    articles: data
                }
                updateMaterialArticle(wxMpMaterialArticleUpdate).then(res => {
                    this.$exMod.ajaxMessage(res);
                    if (res.code === 0) {
                        this.visible = false;
                        this.$emit('closeModal', {render: true});
                    }
                })
            },
            //保存图文素材
            saveNewsMaterial() {
                this.errmsg = "";
                if (this.newsList.length === 0) {
                    this.errmsg += "请至少变编写一篇图文素材<br>";
                } else {
                    for (let i = 0; i < this.newsList.length; i++) {
                        this.validator(i, this.newsList[i]);
                    }
                }
                if (this.errmsg.length > 0) {
                    this.$notification.error({message: '图文表单验证失败', description:this.errmsg })
                    return false;
                }
                //没有错误信息 开始进行数据填充
                let data = {articleList: this.newsList}
                addNewsMaterial(data).then(res => {
                    this.$exMod.ajaxMessage(res);
                    if (res.code === 0) {
                        this.visible = false;
                        this.$emit('closeModal', {render: true});
                    }
                })
            },
            //添加对象
            onAddItem() {
                const size = this.newsList.length + 1;
                if (size > 8) {
                    alert("同一个图文素材最多不超过8条图文");
                    return false
                }
                let item = {
                    title: "请设置图文标题",
                    digest: "",
                    thumbMediaId: "",
                    thumbUrl: "", //封面素材地址
                    author: "",
                    content: "",
                    contentSourceUrl: "", //原文地址
                    showCoverPic: false, //封面显示设置
                    url: "",
                    needOpenComment: false, //是否打开评论
                    onlyFansCanComment: false //是否粉丝才可评论
                }
                this.newsList.push(item);
                this.dataIndex = this.newsList.length - 1;
            },
            onRemove(key) {
                this.newsList = this.newsList.filter(function (item, index, arr) {
                    return index !== key;
                });
                const length = this.newsList.length;
                if (length > 0) {
                    this.dataIndex = 0
                } else {
                    this.dataIndex = -1
                }
            },
            //上移
            indexUp(index) {
                if (index !== 0) {
                    this.newsList[index] = this.newsList.splice(index - 1, 1, this.newsList[index])[0];
                } else {
                    this.newsList.push(this.newsList.shift());
                }
            },
            //下移
            indexDown(index) {
                if (index !== this.newsList.length - 1) {
                    this.newsList[index] = this.newsList.splice(index + 1, 1, this.newsList[index])[0];
                } else {
                    this.newsList.unshift(this.newsList.splice(index, 1)[0]);
                }
            },
            //验证表单数据是否合法
            validator(index, obj) {
                const _this = this;
                //表单数据验证规则
                const validator = new Schema(this.rules);
                validator.validate(obj, (errors) => {
                    if (errors) {
                        for (let i = 0; i < errors.length; i++) {
                            _this.errmsg += "  第" + (index + 1) + "图文:" + errors[i].message ;
                        }
                    }
                });
            return true
            },
            async init() {
                if (this.mediaId != null) {
                    this.isUpdate = true;
                    this.title = "编辑图文素材";
                    await getMaterialNews(this.mediaId).then(res => {
                        if (res.code === 0) {
                            this.newsList = res.data.result
                        }
                    })
                }else{
                    this. onAddItem();
                }
            }
        },
        created() {
            this.init();
        }
    };
</script>
